/* Make a simple routing table
 *
 */

package org.kth.dks.test_bed;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;

import org.kth.dks.dks_comm.DKSRef;

class RoutingTable {
  Hashtable nodes = null;

  public RoutingTable() {
    nodes = new Hashtable();
    load();
  }

  Vector getAll() {
    Vector res = new Vector();
    Object [] objs;

    objs = nodes.values().toArray();
    for( int i = objs.length-1 ; i >= 0 ; i-- ) {
      DKSRef dksRef = (DKSRef) objs[i];
      String temp = dksRef.getID() + "@" + dksRef.getPort() + "@" + dksRef.getIP();
      res.addElement( temp );
    }

    return res;
  }

  DKSRef getDKSRef(int id) {
    return (DKSRef) nodes.get(new Integer(id));
  }

  void load() {
    try {
      nodes.clear();

      FileReader fr = new FileReader("Routing.txt");
      BufferedReader br = new BufferedReader(fr);
      String data = null;

      while ( (data = br.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(data);
        if (st.countTokens() == 3) {
          int id = Integer.parseInt(st.nextToken());
          int port = Integer.parseInt(st.nextToken());
          String ip = st.nextToken();

          nodes.put(new Integer(id), DKSRef.newDKSRef("dks://"+ip+":"+port+"/0/"+id+"/0"));
        } //if
      } //while

      br.close();
      fr.close();
    }
    catch (Exception e) {
	System.out.println("ERROR: could not find the file Routing.txt\n       Routing.txt is a textfile with three fields per line separated with space.\n       The first parameter is a node identifier,\n       the second parameter is a port number,\n       and the last field is a IP number.");
	System.exit(1);
    } //catch
  } //Load
}//RoutingTable class
